package com.pandacc.dao;

import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pandacc.common.properties.PropertiesLoader;

/**
 * 给所有DAO对象提供加载本包路径下类同名properties文件的功能。
 * properties文件建议用来存放sql语句
 * @author Administrator
 *
 */
public abstract class SqlLoadedFromPropertiesDAO implements PropertiesLoader{
	
	private Properties prop;
	
	private Log logger  = LogFactory.getLog(SqlLoadedFromPropertiesDAO.class);
	
	protected final String PROPERTIES_SUFFIX = ".properties";

	/**
	 * properties文件只需要加载一次就够了，线程安全的方法
	 */
	public Properties getProperties() throws Exception {
		if (prop == null) {
			synchronized(this){
				if (prop == null) {
					Properties p = new Properties();
					String propName = this.getClass().getSimpleName() + PROPERTIES_SUFFIX;
					logger.info(String.format("Loading properties file: %s", propName));
					InputStream is = this.getClass().getResourceAsStream(propName);
					p.load(is);
					prop = p;
					return p;
				}else{
					return prop;
				}
			}
		}else{
			return prop;
		}
	}
	
	public String loadSql(String propKey) throws Exception{
		String sql;
		try {
			sql = getProperties().getProperty(propKey);
		} catch (Exception e) {
			String msg = String.format("Failed to laod sql with the key: %s, Please check %s.properties file under the same package."
					, propKey, this.getClass().getSimpleName());
			logger.error(msg);
			e.printStackTrace();
			throw new Exception(msg);
		}
		return sql;
	}

}
